<script lang="ts" setup>
import {
  getCurrentInstance,
  reactive,
  ref,
  h
} from "vue";
import type { TableColumnCtx } from "element-plus/es/components/table/src/table-column/defaults";
import Move from "./childComponents/move.vue";
import Put from "./childComponents/put.vue";
import previewImage from "@/components/fsComponents/previewImage/index";
//接口
import {
  getFileServeFileList,
  updateFile,
  deleteFile,
} from "@/api/serveFile/index";
import { ElLoading } from "element-plus";
const { proxy } = getCurrentInstance() as any;
interface User {
  date: string;
  name: string;
  address: string;
  tag: string;
  changeDate: string;
  size: number;
  checkInfo?: any;
  property?: any;
}
const currentPage4 = ref(1);
const pageSize = ref(10);
const dataTotal = ref(0);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`, currentPage4.value);
  getTableList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  getTableList();
};
const tableRef = ref();
//重置表格所有列筛选
const clearFilter = () => {
  tableRef.value!.clearFilter();
};
//过滤文件大小
const filterFileSize = (value: string, row: any) => {
  const arr: any = value.split(",");
  if (arr.length == 2) {
    return row.fileSize >= arr[0] && row.fileSize <= arr[1];
  } else {
    return row.fileSize >= arr[0];
  }
};

//过滤文件类型
const filterFileTypeHandler = (
  value: string,
  row: User,
  column: TableColumnCtx<User>
) => {
  return value == row.checkInfo.value;
};
const tableData = ref<User[]>([]);
//
const putData = ref<any>({});
/*
 *
 */
/*文件修改*/
const put = ref<any>(null); //文件修改组件实例
const handleChangeInfo = (row: any) => {
  put.value.dialogFormVisible = true;
  putData.value = JSON.parse(JSON.stringify(row)); //防止拷贝带来副作用
};
const refreshData = async (val: any) => {
  try {
    await updateFile({
      fileId: putData.value.fileId,
      spaceId: putData.value.spaceId,
      fileName: val.name,
      status: val.status,
      remark: val.cause,
      addressOrgin: val.addressOrgin,
    });
    getTableList();
  } catch (error) {
    console.log(error, "-----", putData.value);
  }
};
/*
 *
 */
/*文件移动*/
const move = ref<any>(null); //文件移动组件实例
const handleChangeMove = (row: any) => {
  console.log(row);
  move.value.drawer = true;
};
/*
 *
 */
/*文件删除*/
const handleDeleteFile = (row: any) => {
  console.log(row);
  ElMessageBox({
    title: "危险操作温馨提示",
    message: h("p", null, [
      h("i", { style: "color: red;font-style: initial;" }, `确定要删除《`),
      h("i", { style: "color: green;font-style: initial;" }, `${row.fileName}`),
      h("i", { style: "color: red;font-style: initial;" }, `》文件吗?`),
    ]),
    showCancelButton: true,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        instance.confirmButtonLoading = true;
        instance.confirmButtonText = "Loading...";
        console.log(instance);
        try {
          await deleteFile({
            fileId: row.fileId,
          });
          setTimeout(async () => {
            await getTableList();
          });
          ElMessage({
            type: "success",
            message: `删除【${row.fileName}】文件成功!`,
          });
        } catch (error) {
          console.log(error);
        } finally {
          instance.confirmButtonLoading = false;
          done();
        }
      } else {
        done();
        ElMessage({
          type: "info",
          message: "取消删除",
        });
      }
    },
  }).then((action) => {
    //动作完成
  });
};
/*
 *
 */
/*动态展示文件单位大小*/
const showSize: any = (val: any) => {
  if (val >= 1 * 1024 * 1024 * 1024 * 1024) {
    return {
      type: "danger",
      value: parseFloat((val / (1024 * 1024 * 1024 * 1024)).toFixed(2)) + "TB",
    };
  } else if (val >= 1 * 1024 * 1024 * 1024) {
    return {
      type: "warning",
      value: parseFloat((val / (1024 * 1024 * 1024)).toFixed(2)) + "GB",
    };
  } else if (val >= 1 * 1024 * 1024) {
    return {
      type: "success",
      value: parseFloat((val / (1024 * 1024)).toFixed(2)) + "MB",
    };
  } else if (val >= 1 * 1024) {
    return {
      type: "primary",
      value: parseFloat((val / 1024).toFixed(2)) + "KB",
    };
  } else {
    return {
      type: "info",
      value: val + "B",
    };
  }
};
/*
 *
 */
/*获取表格文件列表*/
let current_spaceId = "";
let current_inputValue = "";
const setSpaceId = (val: any) => {
  current_spaceId = val.spaceId;
  current_inputValue = val.inputValue;
};
const getTableList = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  try {
    let data: any = await getFileServeFileList({
      pageNum: currentPage4.value,
      pageSize: pageSize.value,
      spaceId: current_spaceId ? current_spaceId : undefined,
      keyword: current_inputValue ? current_inputValue : undefined,
    });
    dataTotal.value = data.total;
    addFileType(data.list);
  } catch (error) {
    tableData.value = [];
    console.log(error);
  } finally {
    loading.close();
  }
};
/*
 *文件预览
 */
const preView = (row: any) => {
  previewImage({
    urlList: [row.fileFullPath],
  });
};
/*
 *
 */
/*添加文件类型*/
const addFileType = (arr: any) => {
  if (proxy.$gf.gdt(arr) == "array" && arr.length > 0) {
    arr = JSON.parse(JSON.stringify(arr));
    arr.forEach((element: any) => {
      element.checkInfo = proxy.$gf.gft(element.fileName);
    });
    tableData.value = arr;
  } else {
    tableData.value = [];
  }
  console.log(tableData.value);
};
/*
 *
 */
/*获取文件服务空间*/
const serveFileList = ref<any>([]);
const getServeFileList = async () => {
  let data: any = await getServeFileList();
  if (proxy.$gf.gdt(data) == "array" && data.length > 0) {
    serveFileList.value = data;
  }
};
const showButtons = ref(-1);
//复制链接
const handleCopy = (val: string) => {
  navigator.clipboard
    .writeText(val)
    .then(() => {
      ElMessage({
        type: "success",
        message: `链接复制成功`,
      });
    })
    .catch((err) => {
      ElMessage({
        type: "error",
        message: `复制失败:${err}`,
      });
    });
};
defineExpose({
  getTableList,
  setSpaceId,
});
/*
 *
 */
// onMounted(() => {
//   getTableList();
// });
</script>

<template>
  <Move ref="move"></Move>
  <Put ref="put" :data="putData" @refreshData="refreshData"></Put>
  <div class="list-container">
    <div style="height: 40px; display: flex; align-items: center">
      <el-button @click="clearFilter">重置所有表单筛选</el-button>
    </div>

    <el-table
      ref="tableRef"
      row-key="date"
      :data="tableData"
      style="width: 100%"
      :border="true"
      :stripe="true"
    >
      <el-table-column
        label="类型"
        :align="'center'"
        width="80"
        :filters="[
          { text: '图片', value: '1' },
          { text: '视频', value: '2' },
          { text: '文档', value: '3' },
          { text: '音频', value: '4' },
          { text: '压缩包', value: '5' },
          { text: '文件夹', value: '6' },
          { text: '其他', value: '7' },
        ]"
        :filter-method="filterFileTypeHandler"
      >
        <template #default="scope">
          <img
            style="width: 100%; height: 100%"
            :src="`/src/assets/image/ServeFile/sf${scope.row.checkInfo.value}.svg`"
            alt=""
          />
        </template>
      </el-table-column>
      <el-table-column prop="fileName" label="文件名" width="200" />

      
      <el-table-column width="300" prop="fileFullPath" label="文件地址">
        <template #default="scope">
          <div
            class="really-content"
            @mouseenter="showButtons = scope.$index"
            @mouseleave="showButtons = -1"
          >
            <span>
              {{ scope.row.fileFullPath }}
            </span>
            <div v-if="showButtons === scope.$index" class="overlay-buttons">
              <el-button
                type="primary"
                link
                size="large"
                @click="preView(scope.row)"
              >
                <el-icon>
                  <svg
                    viewBox="0 0 1024 1024"
                    xmlns="http://www.w3.org/2000/svg"
                    data-v-746b41f0=""
                  >
                    <path
                      fill="currentColor"
                      d="M512 160c320 0 512 352 512 352S832 864 512 864 0 512 0 512s192-352 512-352zm0 64c-225.28 0-384.128 208.064-436.8 288 52.608 79.872 211.456 288 436.8 288 225.28 0 384.128-208.064 436.8-288-52.608-79.872-211.456-288-436.8-288zm0 64a224 224 0 1 1 0 448 224 224 0 0 1 0-448zm0 64a160.192 160.192 0 0 0-160 160c0 88.192 71.744 160 160 160s160-71.808 160-160-71.744-160-160-160z"
                    ></path>
                  </svg> </el-icon
                ><span>预览文件</span>
              </el-button>
              <el-button
                type="primary"
                link
                size="large"
                @click="handleCopy(scope.row.fileFullPath)"
                ><el-icon><DocumentCopy /></el-icon>复制链接</el-button
              >
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="文件访问状态" width="180">
        <template #default="scope">
          {{ scope.row.status == 1 ? "可访问" : "暂停访问" }}
        </template>
      </el-table-column>
      <el-table-column prop="addressOrgin" label="文件地址来源" width="180">
        <template #default="scope">
          {{ scope.row.addressOrgin == 1 ? "node服务器" : "网络地址" }}
        </template>
      </el-table-column>
      <el-table-column
        prop="fileSize"
        label="文件大小"
        width="100"
        :filters="[
          { text: '0MB~2MB', value: '0,2097152' },
          { text: '2MB~4MB', value: '2097152,4194304' },
          { text: '4MB~8MB', value: '4194304,8388608' },
          { text: '>=8MB', value: '8388608' },
        ]"
        :filter-method="filterFileSize"
        filter-placement="bottom-end"
      >
        <template #default="scope">
          <el-tag
            :type="showSize(scope.row.fileSize).type"
            disable-transitions
            >{{ showSize(scope.row.fileSize).value }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        prop="creatTime"
        label="创建时间"
        sortable
        width="180"
        column-key="date"
      />
      <el-table-column
        prop="updateTime"
        label="修改时间"
        sortable
        width="180"
        column-key="changeDate"
      />
      <el-table-column prop="remark" label="文件备注信息" width="180" />
      <el-table-column fixed="right" label="操作" width="180">
        <template #default="scope">
          <div class="controlBtn">
            <el-button
              type="primary"
              size="small"
              @click="handleChangeInfo(scope.row)"
            >
              <el-icon>
                <EditPen />
              </el-icon>
              <span>修改</span>
            </el-button>

            <el-button
              type="warning"
              size="small"
              disabled
              @click="handleChangeMove(scope.row)"
            >
              <el-icon>
                <svg
                  width="32"
                  height="32"
                  viewBox="0 0 32 32"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                  data-v-746b41f0=""
                >
                  <path
                    d="M32 0H0V32H32V0Z"
                    fill="white"
                    fill-opacity="0.01"
                  ></path>
                  <path
                    d="M15.9945 4H4V28H16"
                    stroke="#fff"
                    stroke-width="2.5"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  ></path>
                  <path
                    d="M22 22L28 16L22 10"
                    stroke="#fff"
                    stroke-width="2.5"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  ></path>
                  <path
                    d="M10.6667 15.9949H28.0001"
                    stroke="#fff"
                    stroke-width="2.5"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  ></path>
                </svg>
              </el-icon>
              <span>移动</span>
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteFile(scope.row)"
            >
              <el-icon>
                <Delete />
              </el-icon>
              <span>删除</span>
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div style="height: 60px"></div>
  </div>
  <div class="pagination-end">
    <el-pagination
      v-model:currentPage="currentPage4"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40,50]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="dataTotal"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      prev-text="上一页"
      next-text="下一页"
    >
    </el-pagination>
  </div>
</template>
<style lang="scss" scoped>
.really-content {
  min-height: 60px;
  display: flex;
  align-items: center;
  position: relative;
  word-break: break-all;
  .overlay-buttons {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.6);
    display: flex;
    align-items: center;
    justify-content: space-evenly;
  }
}

.list-container {
  padding: 0px 20px 20px;
  box-sizing: border-box;
  width: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}
.controlBtn {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  .el-button + .el-button {
    margin-left: 0px;
  }

  .el-button {
    margin: 5px 0px;
  }
}

.pagination-end {
  position: sticky;
  padding: 20px;
  box-sizing: border-box;
  bottom: 0;
  width: 100%;
  z-index: 999;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: start;
  background-color: #fff;
}
</style>
